package com.atguigu.JDBC;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author haoranlu
 * @project IntelliJ IDEA
 */
public class BasicDAO<T> {
    private Class<T> type;
    public BasicDAO(){
        Class<? extends BasicDAO> clazz = this.getClass();
        Type t = clazz.getGenericSuperclass();
        ParameterizedType pt = (ParameterizedType) t;
        Type[] types = pt.getActualTypeArguments();
        type = (Class<T>) types[0];

    }



    public int update(String sql,Object...args) throws SQLException {
        Connection conn = JDBCToolsV4.getConnection();
        PreparedStatement pst = conn.prepareStatement(sql);
        if (args!=null && args.length>0) {
            for (int i = 0; i < args.length; i++) {
                pst.setObject(i+1,args[i]);
            }
        }
        int len = pst.executeUpdate();
        pst.close();
        return len;
    }
    public T getBean(String sql,Object...args) throws Exception {
        Connection conn = JDBCToolsV4.getConnection();
        PreparedStatement pst = conn.prepareStatement(sql);
        if (args!=null && args.length>0){
            for (int i = 0; i < args.length; i++) {
                pst.setObject(i+1,args[i]);
            }
        }
        T t = type.newInstance();
        ResultSet rs = pst.executeQuery();
        ResultSetMetaData metaData = rs.getMetaData();
        int counts = metaData.getColumnCount();
        if (rs.next()){
            for (int i = 0; i < counts; i++) {
                Field field = type.getDeclaredField(metaData.getColumnLabel(i+1));
                field.setAccessible(true);
                field.set(t,rs.getObject(i+1));
            }
        }
        rs.close();
        pst.close();
        return t;
    }
    public List<T> getBeanList(String sql,Object...args) throws Exception{
        Connection conn = JDBCToolsV4.getConnection();
        PreparedStatement pst = conn.prepareStatement(sql);
        if (args!=null && args.length>0){
            for (int i = 0; i < args.length; i++) {
                pst.setObject(i+1,args[i]);
            }
        }
        ResultSet rs = pst.executeQuery();
        ArrayList<T> list = new ArrayList<T>();
        ResultSetMetaData metaData = rs.getMetaData();
        int counts = metaData.getColumnCount();
        while (rs.next()){
            T t = type.newInstance();
            for (int i = 0; i < counts; i++) {
                Field field = type.getDeclaredField(metaData.getColumnLabel(i+1));
                field.setAccessible(true);
                field.set(t,rs.getObject(i+1));
            }
            list.add(t);
        }
        rs.close();;
        pst.close();
        return list;
    }
}
